/**
 * 
 */
package com.nithya.hms;

import java.util.Calendar;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class MainController {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@RequestMapping("index.do")
	public ModelAndView index(HttpServletRequest request,
			HttpServletResponse response) {
		return new ModelAndView("index");
	}

	@RequestMapping("secure/patient-home.do")
	public ModelAndView patientHome(HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView modelAndView = new ModelAndView("patient-home");
		List<Doctor> list = getDocList();
		String doctorIdStr = request.getParameter("doctorId");
		String timeStr = request.getParameter("time");
		if (doctorIdStr != null && timeStr==null) {
			List<Integer> times = getTimes(request);
			modelAndView.addObject("times", times);
		}else if(doctorIdStr!=null && timeStr!=null){
			addOppointments(request);
			return new ModelAndView("redirect:/index.do");
		}
		modelAndView.addObject("list", list);
		return modelAndView;
	}

	private void addOppointments(HttpServletRequest request) {
		String doctorIdStr = request.getParameter("doctorId");
		String timeStr = request.getParameter("time");
		HttpSession session = request.getSession();
		Patient patient = (Patient) session.getAttribute("patient");
		String sql = "insert into appointments (doctor_id, patient_id, time) values (?,?,?)";
		Object[] args = { Integer.parseInt(doctorIdStr), patient.getId(), Integer.parseInt(timeStr)};
		jdbcTemplate.update(sql, args);
	}

	private List<Integer> getTimes(HttpServletRequest request) {
		String sql = "select time from doctor_schedules where doctor_id = ? and day = ?";
		String docIdStr = request.getParameter("doctorId");
		Calendar calendar = Calendar.getInstance();
		Object[] args = { Integer.parseInt(docIdStr),
				calendar.get(Calendar.DAY_OF_WEEK) };
		List<Integer> times = jdbcTemplate.queryForList(sql, args,
				Integer.class);
		return times;
	}

	@RequestMapping("login.do")
	public ModelAndView login(HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView mv = loginPatient(request);
		if (mv != null) {
			return mv;
		}
		return loginDoctor(request);
	}

	private ModelAndView loginDoctor(HttpServletRequest request) {
		String sql = "select * from doctors where email_id = ? and password = ?";
		String emailId = request.getParameter("emailId");
		String password = request.getParameter("password");
		try {
			Doctor doctor = jdbcTemplate.queryForObject(sql,
					new BeanPropertyRowMapper<Doctor>(Doctor.class), emailId,
					password);
			HttpSession session = request.getSession();
			session.setAttribute("doctor", doctor);
			return new ModelAndView("redirect:secure/doctor-home.do");
		} catch (EmptyResultDataAccessException e) {
			return new ModelAndView("redirect:index.do", "error",
					"Invalid user name / password!!!");
		}
	}

	private ModelAndView loginPatient(HttpServletRequest request) {
		String sql = "select * from patients where email_id = ? and password = ?";
		String emailId = request.getParameter("emailId");
		String password = request.getParameter("password");
		try {
			Patient patient = jdbcTemplate.queryForObject(sql,
					new BeanPropertyRowMapper<Patient>(Patient.class), emailId,
					password);
			HttpSession session = request.getSession();
			session.setAttribute("patient", patient);
			return new ModelAndView("redirect:secure/patient-home.do");
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

	@RequestMapping("secure/doctor-home.do")
	public ModelAndView doctorHome(HttpServletRequest request,
			HttpServletResponse response) {
		String sql = "select a.id, concat(p.first_name, p.last_name) as patient_name, time from appointments a join patients p on a.patient_id=p.id where date(cr_date)=curdate() and a.doctor_id = ?";
		HttpSession session = request.getSession();
		Doctor doctor = (Doctor) session.getAttribute("doctor");
		Object[] args = { doctor.getId() };
		List<Appointment> list = jdbcTemplate.query(sql, args, new BeanPropertyRowMapper<Appointment>(Appointment.class));
		return new ModelAndView("doctor-home", "list", list);
	}

	@RequestMapping("sign-up.do")
	public ModelAndView signUp(HttpServletRequest request,
			HttpServletResponse response) {
		return new ModelAndView("sign-up");
	}

	@RequestMapping("secure/logout.do")
	public ModelAndView logout(HttpServletRequest request,
			HttpServletResponse response) {
		HttpSession session = request.getSession();
		session.invalidate();
		return new ModelAndView("redirect:/index.do");
	}

	@RequestMapping("secure/add-doctor.do")
	public ModelAndView addDoctor(HttpServletRequest request,
			HttpServletResponse response) {
		List<Doctor> list = getDocList();
		return new ModelAndView("add-doctor", "list", list);
	}

	private List<Doctor> getDocList() {
		String sql = "select * from doctors";
		List<Doctor> list = jdbcTemplate.query(sql,
				new BeanPropertyRowMapper<Doctor>(Doctor.class));
		return list;
	}

	@RequestMapping("secure/save-doctor.do")
	public ModelAndView addDoctor(HttpServletRequest request,
			HttpServletResponse response, Doctor doctor) {

		String sql = "insert into doctors (first_name, last_name, email_id, password, mobile) values (?,?,?,?,?)";
		Object[] args = { doctor.getFirstName(), doctor.getLastName(),
				doctor.getEmailId(), doctor.getPassword(), doctor.getMobile() };
		jdbcTemplate.update(sql, args);
		return addDoctor(request, response);
	}

	@RequestMapping("save-patient.do")
	public ModelAndView addPatient(HttpServletRequest request,
			HttpServletResponse response, Patient patient) {

		String sql = "insert into patients (first_name, last_name, email_id, password, mobile) values (?,?,?,?,?)";
		Object[] args = { patient.getFirstName(), patient.getLastName(),
				patient.getEmailId(), patient.getPassword(),
				patient.getMobile() };
		jdbcTemplate.update(sql, args);
		return new ModelAndView("redirect:/index.do");
	}

	@RequestMapping("secure/doctor-schedule.do")
	public ModelAndView doctorSchedule(HttpServletRequest request,
			HttpServletResponse response) {
		HttpSession session = request.getSession();
		Doctor doctor = (Doctor) session.getAttribute("doctor");
		String sql = "select concat(day, '_', time) from doctor_schedules where doctor_id = ?";
		Object[] args = { doctor.getId() };
		List<String> list = jdbcTemplate.queryForList(sql, args, String.class);
		return new ModelAndView("doctor-schedule", "list", list);
	}

	@RequestMapping("secure/update-schedule.do")
	public ModelAndView updateSchedule(HttpServletRequest request,
			HttpServletResponse response) {
		HttpSession session = request.getSession();
		Doctor doctor = (Doctor) session.getAttribute("doctor");
		String sql = "delete from doctor_schedules where doctor_id = ?";
		Object[] args = { doctor.getId() };
		jdbcTemplate.update(sql, args);

		Enumeration<?> names = request.getParameterNames();

		while (names.hasMoreElements()) {
			String key = (String) names.nextElement();
			if (key.startsWith("schedules")) {
				String value = request.getParameter(key);
				sql = "insert into doctor_schedules (doctor_id, day, time) values (?,?,?)";
				String[] values = value.split("_");
				Object[] newArgs = { doctor.getId(),
						Integer.parseInt(values[0]),
						Integer.parseInt(values[1]) };
				jdbcTemplate.update(sql, newArgs);
			}
		}

		return new ModelAndView("redirect:doctor-schedule.do");
	}

}
